package ssh

import (
	"fmt"
	"github.com/spf13/viper"
	"golang.org/x/crypto/ssh"
	"time"
)

// 创建 ssh 客户端
var sshClient *ssh.Client

func Init() (err error) {
	// 读取配置文件
	sshHost := viper.GetString("ssh.host")

	sshUser := viper.GetString("ssh.username")

	sshPassword := viper.GetString("ssh.password")

	sshType := "password"

	sshPort := viper.GetInt("ssh.port")

	//创建sshp登陆配置

	config := &ssh.ClientConfig{

		Timeout:         5*time.Second,//ssh 连接time out 时间一秒钟, 如果ssh验证错误 会在一秒内返回

		User:            sshUser,

		HostKeyCallback: ssh.InsecureIgnoreHostKey(), //这个可以, 但是不够安全

		//HostKeyCallback: hostKeyCallBackFunc(h.Host),

	}

	if sshType == "password" {

		config.Auth = []ssh.AuthMethod{ssh.Password(sshPassword)}

	}

	//dial 获取ssh client

	addr := fmt.Sprintf("%s:%d", sshHost, sshPort)

	sshClient, err = ssh.Dial("tcp", addr, config)

	if err != nil {


		return

	}
	return
}

func Close() {
	_ = sshClient.Close()
}
